from yaaps.response import WSGIHtmlResponse
from yaaps.urls import add_url
from yaaps.forms import YaapsForm, YaapsTextField

class LoginForm(YaapsForm):
    def __init__(self, values):
        YaapsForm.__init__(self, values)
        self.fields = [YaapsTextField("username"), YaapsTextField("password")]

def home_page(request):
    if request.session.get("loggedin") == "yes":
        return WSGIHtmlResponse(headers = {}, content="<html>Hello logged in user</html>")
    else:
        return WSGIHtmlResponse(headers = {}, content="<html>Hello there</html>")

def login(request, login_form):
    if login_form.errors:
        return WSGIHtmlResponse(headers = {}, content="<html>Incorrect form</html>")
    else:
        request.session["loggedin"] = "yes"
        return WSGIHtmlResponse(headers = {}, content="<html>Hello, " + login_form['username'][0] + "</html>")

def logout(request):
    request.session.new_session()
    return WSGIHtmlResponse(headers = {}, content="<html>You are now logged out</html>")    

def profile(request, user_name):
    return WSGIHtmlResponse(headers = {}, content="<html>Profile page for " + user_name + "</html>")

add_url('/login', login, "login", "GET", LoginForm)
add_url('/logout', logout, "logout")
add_url('/profile/(?P<user_name>\w+)/', profile, "profile")
add_url('/', home_page, "home-page")
